package com.maidada.mddaichat.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.maidada.mddaichat.common.ErrorCode;
import com.maidada.mddaichat.common.ResultUtils;
import com.maidada.mddaichat.util.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token拦截器
 *
 * @author wulinxuan
 * @date 2025-04-16 17:36
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的 Token
        String token = request.getHeader("X-Access-Token");

        // 检查 Token 是否为空
        if (token == null || token.isEmpty()) {
            ResultUtils.setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, ErrorCode.NOT_LOGIN_ERROR);
            return false;
        }

        try {
            // 校验 Token 的合法性
            JwtUtils.verifyToken(token);
            return true;
        } catch (JWTVerificationException e) {
            // Token 校验失败
            ResultUtils.setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, ErrorCode.TOKEN_INVALID);
            return false;
        }
    }
}